import React, { useEffect, useState } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import TitleBar from '@/src/components/titleBar';
import './index.less';
import { Image, View } from '@tarojs/components';
import store from '@/src/store';
import {
  cancelSignUpFun,
  myListFun,
  queryQrCodeFun,
  verifyFun,
} from '@/src/common/method/activityFun';
import BottomContainer from '@/src/components/bottomContainer';
import MineItem from '@/src/components/mineItem';
import CommonBlank from '@/src/components/pageBlank';
import { AtCurtain } from 'taro-ui';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { observer } from 'mobx-react-lite';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { getNetWorkStatus } from '@/src/common/util/util';
//我的活动
const MineActivity = () => {
  const [dataList, setDataList] = useState<any>([]);
  const [loadingText, setLoadingText] = useState<any>('加载中');
  const [base64Str, setBase64Str] = useState<any>('');
  const [isOpened, setIsOpened] = useState<boolean>(false);
  const [verifyied, setVerifyied] = useState<boolean>(false); //是否核销
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  const getList = () => {
    myListFun({
      userId: Taro.getStorageSync('userId'),
      phoneNumber: Taro.getStorageSync('mobile'),
    })
      .then((res: any) => {
        setLoadingText('');
        setDataList(res.list);
      })
      .catch((err: any) => {
        setLoadingText('');
      });
  };
  //取消报名
  const cancelActivity = (id: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    cancelSignUpFun({
      orderId: id,
      userId: Taro.getStorageSync('userId'),
      deleteFlag: '0',
    })
      .then((res: any) => {
        if (res.code === '0') {
          showToast('取消成功', 'success');
          getList();
        } else if (res.code !== '0' && res.mag) {
          showToast(res.msg);
        }
      })
      .catch((e: any) => {
        showToast('取消失败', 'error');
      });
  };
  const reviewClick = (id: any) => {
    Taro.navigateTo({
      url: `/subPagesActivity/review/index?activityId=${encodeURIComponent(id)}`,
    });
  }
  //删除报名
  const deleteActivity = (id: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    cancelSignUpFun({
      orderId: id,
      userId: Taro.getStorageSync('userId'),
      deleteFlag: '1',
    })
      .then((res: any) => {
        Taro.showToast({ title: '删除成功', icon: 'none' });
        getList();
      })
      .catch((e: any) => {
        Taro.showToast({ title: '删除失败', icon: 'none' });
      });
  };

  //查看活动二维码
  const queryQrCode = (orderId: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    queryQrCodeFun({ orderId: orderId }).then((res: any) => {
      setBase64Str(res.qrCodeBase64);
      setIsOpened(true);
      const verifiyVal: any = dataList.filter(
        (item: any) => item.orderId === orderId
      )[0];
      setVerifyied(verifiyVal.hasVerified);
    });
  };
  //扫码核销
  const scanCodeClick = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.scanCode({
      onlyFromCamera: true, // 仅允许相机扫码（禁止相册）
      scanType: ['qrCode'],
    }).then((res: any) => {
      // Taro.showToast({ title: res.result, icon: 'none' });
      verifyFun({
        orderId: res.result,
        phoneNumber: Taro.getStorageSync('mobile'),
      })
        .then((res: any) => {
          console.warn('核销结果', res);

          if (String(res.code) === '0') {
            Taro.showToast({ title: '核销成功', icon: 'none' });
            getList();
          } else {
            Taro.showToast({ title: res.message, icon: 'none' });
          }
        })
        .catch((err: any) => {
          // Taro.showToast({ title: err.message, icon: 'none' });
          getList();
        });
    });
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <View
      className="mine-activity-container"
      style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="我的活动" />
      {dataList && dataList.length > 0 && (
        <View
          className="mine-activity-content"
          style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
        >
          <MineItem
            list={false}
            dataList={dataList}
            queryQrCode={(orderId) => queryQrCode(orderId)}
            activityClick={() => scanCodeClick()}
            reviewClick={(id:any) => reviewClick(id)}
            cancelClick={(id:any) => cancelActivity(id)}
            deleteClick={(id:any) => deleteActivity(id)}
          />
        </View>
      )}
      {dataList && dataList.length === 0 && loadingText === '' && (
        <CommonBlank
          blank={
            'https://file.linkcook.cn/image/wineMiniProgram/exception/empty_activity.png'
          }
          visible={true}
          desc="抱歉，暂无活动"
        />
      )}
      <AtCurtain isOpened={isOpened} onClose={() => setIsOpened(false)}>
        <View className="qr-code-container">
          <View className="qr-code-title">活动二维码</View>
          {base64Str && (
            <Image
              className="qr-code-image"
              mode="widthFix"
              src={`data:image/png;base64,${base64Str}`}
            />
          )}
          <View className="qr-code-desc">
            ({verifyied ? '已核销' : '未核销'})
          </View>
        </View>
      </AtCurtain>
      <StatusToast />
      <BottomContainer />
    </View>
  );
};

export default observer(MineActivity);
